package com.sh.personnel.controller.sys;

import com.sh.personnel.domain.ITbMenu;
import com.sh.personnel.security.util.SecurityUtil;
import com.sh.personnel.service.IMenuService;
import com.sh.personnel.util.result.Result;
import com.sh.personnel.vo.dto.MenuDto;
import com.sh.personnel.vo.dto.MenuTreeDto;
import com.sh.personnel.vo.dto.SelectTreeDto;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单控制
 * @author 林思浩
 * @date 2020/03/13 13:35
 */
@RestController
@RequestMapping("/menu")
public class IMenuController {

    @Autowired
    IMenuService menuService;

    //获取用户菜单路由树
    @GetMapping("/tree")
    public Result getUserMenuTree() {
        List<MenuTreeDto> list = menuService.generateMenuTree(SecurityUtil.getUser().getUserId());
        return Result.success().setData("menu_tree", list);
    }

    /**
     * 获取所有菜单权限选择树（包含按钮）
     * @param type //带任意参数则获取所有上级菜单选择树（不包含按钮）
     * @return
     */
    @GetMapping("/select")
    public Result getSelectMenuAllTree(@RequestParam(required = false) String type) {
        List<SelectTreeDto> selectMenus = menuService.generateSelectMenuTree(type);
        return Result.success().setData("select_menus", selectMenus);
    }

    //获取菜单列表
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:view')")
    public Result getMenuAllList(@RequestParam(required = false) String key) {
        List<MenuDto> menusList = menuService.getMenuAllList(key);
        return Result.success().setData("menus_list", menusList);
    }

    //获取菜单信息
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:menu:info')")
    public Result getMenuById(@PathVariable String id) {
        ITbMenu menu = menuService.getMenuById(id);
        return Result.success().setData("menu", menu);
    }

    //添加菜单
    @PostMapping
    @PreAuthorize("hasAuthority('sys:menu:insert')")
    public Result addMenu(@RequestBody ITbMenu menu) {
        boolean bool = menuService.addMenu(menu);
        return bool ? Result.success() : Result.fail();
    }

    //更新菜单
    @PutMapping
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result updateMenu(@RequestBody ITbMenu menu) {
        boolean bool = menuService.updateMenuById(menu);
        return bool ? Result.success() : Result.fail();
    }

    //删除菜单
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result deleteMenu(@PathVariable String id) {
        boolean bool = menuService.deleteMenuById(id);
        return bool ? Result.success() : Result.fail();
    }

}
